from playwright.sync_api import sync_playwright, TimeoutError
import time

def get_cookie():
    try:
        with sync_playwright() as p:
            browser = p.chromium.launch(headless=False, channel="chrome")
            context = browser.new_context()
            page = context.new_page()

            try:
           # 更新为获取特定文件夹的Cookie
           page.goto("https://pan.xunlei.com/?path=%2F%E6%88%91%E7%9A%84%E8%B5%84%E6%BA%90")
           print("请确保已登录并访问目标文件夹，然后按回车继续...")
           input()

           # 获取当前页面的所有Cookie
           cookies = context.cookies()
           valid_cookies = [c for c in cookies if c['name'] in ['xlsec', 'sessionid']]
           cookie_str = "; ".join([f"{c['name']}={c['value']}" for c in valid_cookies])

            except TimeoutError:
                print("页面加载超时，请检查网络连接后重试。")
                browser.close()
                return

            print("请扫码登录迅雷云盘，登录后按回车继续...")
            start_time = time.time()
            timeout = 120  # 设置超时时间为 120 秒

            try:
                input()
            except KeyboardInterrupt:
                print("\n操作被用户取消。")
                browser.close()
                return

            if time.time() - start_time > timeout:
                print(f"登录超时（{timeout}秒），请重新运行脚本并尽快完成登录。")
                browser.close()
                return

            cookies = context.cookies()
            cookie_str = "; ".join([f"{c['name']}={c['value']}" for c in cookies])

            try:
                with open("xunlei_cookie.txt", "w", encoding="utf-8") as f:
                    f.write(cookie_str)
                print("Cookie 已写入 xunlei_cookie.txt 文件。")
            except IOError:
                print("无法写入 xunlei_cookie.txt 文件，请检查文件权限和路径是否正确。")

            browser.close()

    except Exception as e:
        print(f"发生未知错误: {e}")

if __name__ == "__main__":
    get_cookie()
